// 本地应用的数据状态
import { setState } from './index'
import gql from '../utils/nanographql'
import { baseUrl } from '../utils/http'

// 封装微信接口,使其变成promise函数
function apiLogin() {
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => resolve(res.code),
      fail: err => reject(err)
    })
  })
}

function apiGetToken(code) {
  return new Promise((resolve, reject) => {
    const str = `
      mutation ($data:LoginRequest!){
        login(loginRequest:$data){
          token
          tokenHeader
          tokenPrefix
        }
      }
    `
    wx.request({
      url: baseUrl,
      data: gql(str)({ data: { code } }),
      method: 'POST',
      success: res => resolve(res.data.data.login),
      fail: err => reject(err)
    })
  })
}

const state = {
  isFirstIn: true,
  token: null
}

const mutations = { setState }

const actions = {
  async login({ commit }) {
    try {
      const code = await apiLogin()
      const { token, tokenHeader, tokenPrefix } = await apiGetToken(code)
      const tokenObj = {}
      tokenObj[`${tokenHeader}`] = `${tokenPrefix}${token}`
      commit('setState', { token: tokenObj })
    } catch (err) {
      console.error('微信登陆失败', err)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
